<template>
	<div class="content-box add-creation">
		<el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
			<div class="el-form-sub-title">基本信息</div>
			<el-form-item label="活动图片" prop="images">
				<uploadImage v-model:file-list="form.images" :limit="12" :fileSize="300 / 1024">
					<template #tip> 建议尺寸：800*400像素，300kb以下，第一张为默认首图，最多上传12张</template>
				</uploadImage>
			</el-form-item>
			<el-form-item label="活动名称" prop="name">
				<el-input v-model="form.name" placeholder="输入活动名称" />
			</el-form-item>
			<el-form-item label="活动时间" prop="date">
				<el-date-picker v-model="form.date" :disabled="editId" type="datetimerange" start-placeholder="开始时间" end-placeholder="结束时间" />
			</el-form-item>
			<el-form-item label="活动地点" prop="addressCode">
				<CityCascader v-model:label="form.addressLabel" v-model="form.addressCode" class="mb10" />
			</el-form-item>
			<el-form-item label="详细地址" prop="address">
				<el-input v-model="form.address" placeholder="输入详细地址" />
			</el-form-item>
			<el-form-item label="参会人数" prop="count">
				<el-input-number :min="0" class="num-left mr10" :controls="false" v-model="form.count" :max="9999999999" placeholder="输入参会人数">
				</el-input-number>
			</el-form-item>
			<div class="el-form-sub-title">报名管理</div>
			<el-form-item label="报名审核" prop="enableAudit">
				<el-radio-group v-model="form.enableAudit" class="good-type">
					<el-radio :value="true"> 开启</el-radio>
					<el-radio :value="false"> 关闭</el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item label="报名表单" prop="customFormHeaders">
				<el-checkbox-group v-model="form.customFormHeaders">
					<el-checkbox :disabled="item.fixed" style="display: block" class="mt10" v-for="(item, i) in formList" :key="i" :label="i" :value="i">
						{{ item.label }}
						<el-input
							@click.stop="() => {}"
							v-if="!item.fixed"
							class="ml10"
							v-model.trim="item.value"
							@blur="
								() => {
									if (item.value) {
										item.label = item.value;
										item.value = '';
									}
								}
							"
							placeholder="输入标题"
						></el-input>
					</el-checkbox>
				</el-checkbox-group>
			</el-form-item>
			<div class="el-form-sub-title">活动详情</div>
			<el-form-item label="详情介绍" prop="introduction">
				<el-input type="textarea" v-model="form.introduction" :maxlength="1000" rows="10" placeholder="输入介绍内容" show-word-limit></el-input>
			</el-form-item>
			<div class="el-form-sub-title">活动签到</div>
			<el-form-item label="签到设置" prop="enableSignIn">
				<el-radio-group v-model="form.enableSignIn" @change="form.enableCoordinates = false" class="w-full">
					<el-radio :value="true"> 开启 </el-radio>
					<el-radio :value="false"> 关闭 </el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item v-if="form.enableSignIn" label="签到坐标" prop="enableCoordinates">
				<el-radio-group v-model="form.enableCoordinates" class="w-full">
					<el-radio :value="true"> 开启 </el-radio>
					<el-radio :value="false"> 关闭 </el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item v-if="form.enableCoordinates" label="签到经纬度" prop="longlat">
				<!-- longitude latitude -->
				<vueMap keyWord="签到地址" v-model="form.longlat"></vueMap>
			</el-form-item>
			<el-form-item v-if="form.enableCoordinates" label="签到范围" prop="signInRange">
				<el-input-number v-model="form.signInRange" class="num-left" :controls="false" max="999999" placeholder="输入范围(例如：500)">
				</el-input-number
				><span class="ml10">米</span>
			</el-form-item>
			<!-- <el-form-item label="签到积分" v-if="form.enableSignIn" prop="signInGainCredit">
				<el-radio-group v-model="form.signInGainCredit" class="w-full">
					<el-radio :value="true"> 开启 </el-radio>
					<el-radio :value="false"> 关闭 </el-radio>
				</el-radio-group>
			</el-form-item> -->
			<!-- <el-form-item v-if="form.enableSignIn && form.signInGainCredit" label="奖励积分" prop="credit">
				<el-input-number :min="0" class="num-left mr10" :controls="false" v-model="form.credit" :max="9999999999" placeholder="输入积分数量">
				</el-input-number
				>积分
			</el-form-item> -->
			<el-form-item label="签到伴手礼" v-if="form.enableSignIn" prop="signInGift">
				<el-radio-group v-model="form.signInGift" class="w-full">
					<el-radio :value="true"> 开启 </el-radio>
					<el-radio :value="false"> 关闭 </el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item v-if="form.enableSignIn && form.signInGift" label="伴手礼名称" prop="giftName">
				<el-input v-model="form.giftName" :maxlength="50" placeholder="输入伴手礼名称"> </el-input>
			</el-form-item>
			<el-form-item v-if="form.enableSignIn && form.signInGift" label="伴手礼图片" prop="giftImage">
				<uploadImage v-model:file-list="form.giftImage" :limit="1" :fileSize="300 / 1024">
					<template #tip> 建议尺寸：800*800像素，300kb以下</template>
				</uploadImage>
			</el-form-item>
			<el-form-item v-if="form.enableSignIn" label="签到得抽奖" prop="signInGainRaffle">
				<el-radio-group v-model="form.signInGainRaffle" class="w-full">
					<el-radio :value="true"> 开启 </el-radio>
					<el-radio :value="false"> 关闭 </el-radio>
				</el-radio-group>
			</el-form-item>
			<el-form-item v-if="form.enableSignIn && form.signInGainRaffle" label="关联抽奖" prop="raffleId">
				<RefreshSelect
					v-model="form.raffleId"
					filterable
					remote
					:api="fetchLotteryList"
					:apiParams="{ searchType: 'NAME', queryKey: 'keywords' }"
					:option-map="{ label: 'name', value: 'id' }"
					popper-class="refresh-select"
					link="/lottery/list/add"
					placeholder="请选择抽奖活动"
				></RefreshSelect>
			</el-form-item>
			<div class="el-form-sub-title">发布设置</div>
			<el-form-item label="是否公开活动" prop="isPublic">
				<el-radio-group v-model="form.isPublic" class="w-full">
					<el-radio :value="true"> 开启 </el-radio>
					<el-radio :value="false"> 关闭 </el-radio>
				</el-radio-group>
				<p class="el-upload__tip">非公开活动将不会在小程序端活动列表展示，但可通过访问链接进入活动参与报名</p>
			</el-form-item>
			<el-form-item label-width="0">
				<div class="flex-start w-full">
					<el-button @click="back">取消</el-button>
					<el-button type="primary" v-debounce="onSubmit">保存</el-button>
				</div>
			</el-form-item>
		</el-form>
	</div>
</template>

<script setup lang="tsx" name="addActivity">
import { ref, reactive, onBeforeMount, onMounted } from 'vue';
import { ElMessage, type FormRules } from 'element-plus';
import { useRoute, useRouter } from 'vue-router';
import dayjs from 'dayjs';
import uploadImage from '/@/components/upload/image.vue';
import RefreshSelect from '/@/components/refreshSelect/index.vue';
import { fetchUpdateActivity, fetchCreateActivity, fetchActivityDetail } from '/@/api/activity';
import { fetchLotteryList } from '/@/api/lottery';
import CityCascader from '/@/components/cityCascader/index.vue';
import vueMap from '/@/components/vueMap/index.vue';

const route = useRoute();
const router = useRouter();
const formRef = ref();
const form = ref<any>({
	images: [],
	addressCode: [],
	customFormHeaders: [0, 1],
	enableAudit: true,
	enableSignIn: true,
	enableCoordinates: true,
	signInGainCredit: true,
	signInGift: true,
	signInGainRaffle: true,
	isPublic: true,
});
//校验规则
const rules = reactive<FormRules<any>>({
	images: [{ required: true, message: '活动图片不能为空', trigger: ['change', 'blur'] }],
	name: [{ required: true, message: '活动名称不能为空', trigger: ['change', 'blur'] }],
	date: [{ required: true, message: '活动时间不能为空', trigger: ['change', 'blur'] }],
	addressCode: [{ required: true, message: '活动地点不能为空', trigger: ['change'] }],
	address: [{ required: true, message: '详细地址不能为空', trigger: ['change', 'blur'] }],
	count: [{ required: true, message: '参会人数不能为空', trigger: ['change', 'blur'] }],
	enableAudit: [{ required: true, trigger: 'blur', message: '报名审核不能为空' }],
	customFormHeaders: [{ required: true, trigger: 'blur', message: '报名表单不能为空' }],
	introduction: [{ required: true, trigger: 'blur', message: '详情介绍不能为空' }],
	enableSignIn: [{ required: true, message: '签到设置不能为空', trigger: ['change', 'blur'] }],
	enableCoordinates: [{ required: true, message: '签到坐标不能为空', trigger: ['change', 'blur'] }],
	longlat: [{ required: true, message: '签到经纬度不能为空', trigger: ['change', 'blur'] }],
	signInRange: [{ required: true, message: '签到范围不能为空', trigger: ['change', 'blur'] }],
	signInGainCredit: [{ required: true, message: '签到积分不能为空', trigger: ['change', 'blur'] }],
	credit: [{ required: true, message: '奖励积分不能为空', trigger: ['change', 'blur'] }],
	signInGift: [{ required: true, message: '签到伴手礼不能为空', trigger: ['change', 'blur'] }],
	giftName: [{ required: true, message: '伴手礼名称不能为空', trigger: ['change', 'blur'] }],
	giftImage: [{ required: true, message: '伴手礼图片不能为空', trigger: ['change', 'blur'] }],
	signInGainRaffle: [{ required: true, message: '签到得抽奖不能为空', trigger: ['change', 'blur'] }],
	raffleId: [{ required: true, message: '关联抽奖不能为空', trigger: ['change', 'blur'] }],
	isPublic: [{ required: true, message: '是否公开活动不能为空', trigger: ['change', 'blur'] }],
});

const updateVisible = ref(false);
const editId = ref();

const formList = reactive([
	{
		label: '姓名',
		fixed: true,
	},
	{
		label: '手机号',
		fixed: true,
	},
	{
		label: '自定义名称',
		value: '',
	},
	{
		label: '自定义名称',
		value: '',
	},
	{
		label: '自定义名称',
		value: '',
	},
	{
		label: '自定义名称',
		value: '',
	},
	{
		label: '自定义名称',
		value: '',
	},
]);

const formatParams = (data: any) => {
	const params = {
		...data,
		id: editId.value || '',
		images: data.images.map((item: any) => item.url),
		startTime: dayjs(data.date[0]).format('YYYY-MM-DD HH:mm:ss'),
		endTime: dayjs(data.date[1]).format('YYYY-MM-DD HH:mm:ss'),
		customFormHeaders: data.customFormHeaders.filter((i: any) => i > 1).map((item: any) => formList[item].label),
		giftImage: data.giftImage ? data.giftImage.map((item: any) => item.url).join() : '',
	};
	console.log(data);
	if (data.addressCode) {
		params.provinceCode = data.addressCode[0];
		params.cityCode = data.addressCode[1];
		params.districtCode = data.addressCode[2];
	}
	if (data.enableSignIn && data.enableCoordinates && data.longlat) {
		params.longitude = data.longlat?.coord[0];
		params.latitude = data.longlat?.coord[1];
		params.province = data.longlat.city[0];
		params.city = data.longlat.city[1];
		params.district = data.longlat.city[2];
		params.locationDetail = data.longlat.locationDetail;
	}
	if (data.addressLabel) {
		params.provinceName = data.addressLabel[0];
		params.cityName = data.addressLabel[1];
		params.districtName = data.addressLabel[2];
	}
	return params;
};

const onSubmit = async () => {
	formRef.value.validate(async (valid: boolean) => {
		if (valid) {
			const params = formatParams(form.value);
			const res = await (editId.value ? fetchUpdateActivity : fetchCreateActivity)(params);
			if (res.code == 200) {
				ElMessage.success(editId.value ? '编辑成功' : '新增成功');
				back();
			} else {
				ElMessage.error(res.msg);
			}
		}
	});
};

const back = () => {
	router.push('/activity/list');
};

onMounted(async () => {
	editId.value = route.params.id;
	if (editId.value) {
		const res = await fetchActivityDetail({ id: editId.value });
		if (res.code === 200) {
			const data = res.data;
			data.images = data.images.map((item: any) => {
				return {
					url: item,
				};
			});
			data.giftImage = data.giftImage
				? data.giftImage.split(',').map((item: any) => {
						return {
							url: item,
						};
				  })
				: [];
			const customFormHeaders = [0, 1];
			data.customFormHeaders.forEach((item: any, index: number) => {
				formList[index + 2].label = item;
				customFormHeaders.push(index + 2);
			});
			data.longlat = {
				city: [data.province, data.city, data.district],
				locationDetail: data.locationDetail,
				coord: [data.longitude, data.latitude],
			};
			data.customFormHeaders = customFormHeaders;
			data.date = [data.startTime, data.endTime];
			data.addressCode = [data.provinceCode, data.cityCode, data.districtCode];
			data.addressLabel = [data.provinceName, data.cityName, data.districtName];
			form.value = data;
		}
	}
});
</script>

<style scoped lang="scss">
.add-creation {
	.el-form-item {
		.el-input,
		.el-select,
		.el-input-number {
			max-width: 450px;
		}
	}
}
</style>
<style lang="scss">
.add-creation {
	.el-form-item {
		.el-input,
		.el-input-number,
		.el-select,
		.el-date-editor,
		.el-cascader,
		.el-textarea,
		.refresh-select-wrapper {
			width: 100%;
			max-width: 450px;
		}
	}
}
</style>
